package commands;


import java.util.Iterator;
import java.util.Vector;

import nanoxml.XMLElement;
import utils.ITransmittable;
import utils.PlayerList;

/**
 * This command represents a situation when a client joins 
 * an existing table.
 */
public class CommandJoinTable implements ITransmittable {
    
    private final static String ATTR_USER_NAME = "Username";
    private final static String ATTR_TABLE_NUM = "TableNum";
    
    private PlayerList playerList = null;
    private int tableNum;
    private String username = null;
    
    public CommandJoinTable (String username, int tableNum) {
    	this.tableNum = tableNum;
    	this.username = username;
    }
    
    @SuppressWarnings("unchecked")
	public CommandJoinTable (XMLElement message) {
    	this.tableNum = message.getIntAttribute(ATTR_TABLE_NUM);
    	this.username = (String) message.getAttribute(ATTR_USER_NAME);
        Vector<XMLElement> children = message.getChildren();
        for (Iterator<XMLElement> i = children.iterator(); i.hasNext(); ) {
            XMLElement element = (XMLElement)i.next();
            String name = element.getName ();
            if (name.equals (Commands.PLAYER_LIST)) {
                this.playerList = new PlayerList (element);
            }
        }
    }

	public XMLElement toXML () {
		XMLElement element = new XMLElement();
		element.setName(Commands.JOIN_TABLE);
		element.setAttribute(ATTR_USER_NAME, username);
		element.setIntAttribute(ATTR_TABLE_NUM, tableNum);
		if (playerList != null)
			element.addChild (playerList.toXML());
		return element;
	}

    public PlayerList getPlayerList () {
        return playerList;
    }
    public int getTableNum() {
    	return tableNum;
    }
    public String getUsername() {
        return username;
    }
}
